from flask import Flask, request, jsonify
from flask_cors import CORS
from openai import OpenAI
from zhipuai import ZhipuAI

app = Flask(__name__)
CORS(app)

# DeepSeek的访问API
ds_client = OpenAI(api_key="sk-5b2ecd0180d04171a458c6a9af63dc6e", base_url="https://api.deepseek.com")
# 智谱AI的访问API
zhipu_client = ZhipuAI(api_key="5a4bd67b6d854a4cb652fe9ed2b96103.BEAK5sYOZdQs0frK")

# 问答接口
@app.route('/chat', methods=['POST'])
def chat():
    # 从请求中获取参数
    data = request.json
    # 获取发送的问题内容
    question = data['question']
    # 访问DeepSeek获取回答结果
    response = ds_client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "你是个人中文智能助手，对所有问题的回答都需要考虑中文语言环境"},
            {"role": "user", "content": question},
        ],
        stream=False
    )
    # 返回回答结果内容
    return jsonify({"answer": response.choices[0].message.content})


# 绘图接口
@app.route('/draw', methods=['POST'])
def draw():
    # 从请求中获取参数
    data = request.json
    # 获取发送的画图提示词
    question = data['question']
    # 访问智谱绘图获取绘图结果
    response = zhipu_client.images.generations(
        model="cogview-4-250304",  # cogview-4模型收费，cogview-3-flash模型免费
        prompt=question,
    )
    # 返回生成图像的在线地址
    return jsonify({"answer": response.data[0].url})


if __name__ == '__main__':
    app.run(debug=True)
